
var MY_INSTITUTION_REVIEW = (function() {

	var quantity = 0;
	var mainColor = '#01FFFF';

	//获取页面统计信息
	function loadChartInfo() {
		$.ajax({
			type: "POST",
			url: "invs_home_page.do/load_chart_info",
			data: {id : '10'},
			success: function(data) {
				WeKnow.closeLoading();
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

				if (data.errorcode == 0) {
                    var chartInfo = data.chartInfo;

					setSelectpickerOptions(chartInfo.searchTypes);
					//机构总数
					drawInstitutionsTotal(chartInfo.quantity, chartInfo.total);
					//行业类型
					drawInstitutionsTypeList(chartInfo.type);
					//行业
					drawIndustryPie(chartInfo.industry);
					//等级
					drawLevelBar(chartInfo.level);
					//经济性质
					drawEconomicPie(chartInfo.economic);
					//所有权性质
					drawOwnershipBar(chartInfo.ownership);
					//街道分布
					drawDistributionPolar(chartInfo.district);
					//轮动
					drawCarousel(chartInfo.carousel);
				} else if (data.errorcode == -1 ) {
					WeKnow.errorMsg( data.errMsg );
				} else {
					WeKnow.systemMsg('查询失败，请重新登录');
				}
			}
		});
	}

	//机构总数
	function drawInstitutionsTotal(invs, total) {
		if(invs == undefined || invs.length == 0) {
			invs = quantity;
		} else {
			quantity = invs
		}

		if(total == undefined || total.length == 0) {
			total = 0;
		}

		//清空
		document.getElementById("institutionsTotal").innerHTML = "";

		var numbers =  invs.toString();
		var length = total >= invs ? total.toString().length : invs.toString().length;

		for(var i=0; i < 3-length; i++) {
			$("#institutionsTotal").append(
				"<span class='middleAboveNumFont'>" + 0 + "</span>"
			);
		}

		for(var i=0; i < length; i++) {
			$("#institutionsTotal").append(
				"<span class='middleAboveNumFont'>" + numbers[i] + "</span>"
			);
		}

		$("#institutionsTotal").append(
			"<span class='middleAboveFont'>" + '&nbsp;|&nbsp;' + "</span>"
		);

		numbers =  total.toString();
		for(var i=0; i < 3-length; i++) {
			$("#institutionsTotal").append(
				"<span class='middleAboveNumFont'>" + 0 + "</span>"
			);
		}

		for(var i=0; i < length; i++) {
			$("#institutionsTotal").append(
				"<span class='middleAboveNumFont'>" + numbers[i] + "</span>"
			);
		}
	}

	//行业类型
	function drawInstitutionsTypeList(data) {
		if(data == null || data.length == 0) {
			return;
		}

		//清空
		// document.getElementById("institutionsType").innerHTML = "";

		for (var i=0; i < data.length; i++) {
			var optionId = 'option' + data[i].value;
			var temp = document.getElementById(optionId);
			if(temp == null) {
				$("#institutionsType").append(
					"<option id='" + optionId + "' value=" + data[i].value + ">" + data[i].name + "</option>"
				);
			}
		}
	}

	//行业
	function drawIndustryPie(data) {
		if (data == null || data.length == 0) {
			return;
		} else {
			var nameData = [];
			for(var i=0; i < data.length; i++){
				nameData.push(data[i].name);
			}
		}
		// 1. 实例化对象
		var myChart = echarts.init(document.querySelector("#industryPie"));
		// 2. 指定配置项和数据
		option = {
			tooltip : {
				trigger: 'item',
				formatter: "{b}: {c} ({d}%)",
			},
			color: [
				'#FF9F7F',
				"#FEDB5B",
				"#9FE7B9",
				"#66E0E3",
				"#32C4E9",
				"#65A8FF",
				"#D194FF",
				"#9976FB",
				"#FB76A0",
			],
			legend: {
				orient: 'vertical',
				top: fontChart(0.125),
				left: fontChart(0.125),
				itemHeight: fontChart(0.125),
				itemWidth: fontChart(0.1875),
				itemGap: fontChart(0.0625),
				data: nameData,
				textStyle: {
					// fontSize: fontChart(0.15),
					color: '#fff',
					fontSize: fontChart(0.15),
				},
			},
			series : [
				{
					name:'',
					type:'pie',
					// radius : '70%',
					center: ["65%", "50%"],
					itemStyle : {
						normal : {
							label : {
								show : false,
								formatter: "{b}\n{c},{d}%",
								textStyle: {
									color: mainColor  // 改变标示文字的颜色
								}
							},
						},
					},
					/*labelLine : {
						show : true,
						normal:{
							// length: 20,  // 改变标示线的长度
							lineStyle: {
								color: mainColor  // 改变标示线的颜色
							}
						},
					},
					itemStyle : {
						normal : {
							label : {
								show : true,
								formatter: "{b}\n{c} ({d}%)",
								textStyle: {
									color: mainColor  // 改变标示文字的颜色
								}
							},
						},
					},*/
					data: data
				}
			]
		};
		// 3. 配置项和数据给我们的实例化对象
		myChart.setOption(option);
		// 4. 当我们浏览器缩放的时候，图表也等比例缩放
		window.addEventListener("resize", function() {
			// 让我们的图表调用 resize这个方法
			myChart.resize();
		});
	};

	//等级
	function drawLevelBar(data) {
		if (data == null || data.length == 0) {
			return;
		} else {
			var nameData = [];
			var valueData = [];
			for(i=0;i<data.length;i++){
				nameData.unshift(data[i].name);
				valueData.unshift(data[i]);
			}
		}
		// 1. 实例化对象
		var myChart = echarts.init(document.querySelector("#levelBar"));
		// 2. 指定配置项和数据
		option = {
			title: {
				subtext: '机构数',
				subtextStyle: {
					color: mainColor,
				}
			},
			grid:{
				x: 40,
				y: 60,
				x2: 15,
				y2: 25,
			},
			tooltip : {
				trigger: 'axis'
			},
			calculable : true,
			xAxis : [
				{
					type : 'category',
					data : nameData,
					axisLine: {
						lineStyle: {
							color: mainColor
						}
					},
					splitLine: {
						show: false
					},
					axisTick:{
						show:false
					},
				}
			],
			yAxis : [
				{
					type : 'value',
					minInterval: 1,
					axisLine: {
						lineStyle: {
							color: mainColor
						}
					},
					splitLine: {
						show: false
					},
					axisTick:{
						show:false
					},
				}
			],
			series : [
				{
					name:'机构数',
					type:'bar',
					data:valueData,
					itemStyle: {
						normal: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
								offset: 0,
								color: mainColor
							}, {
								offset: 1,
								color: '#195bff'
							}]),
						}
					},
					barWidth: fontChart(0.5),
				}
			]
		};

		// 3. 配置项和数据给我们的实例化对象
		myChart.setOption(option);
		// 4. 当我们浏览器缩放的时候，图表也等比例缩放
		window.addEventListener("resize", function() {
			// 让我们的图表调用 resize这个方法
			myChart.resize();
		});
	};

	//经济
	function drawEconomicPie(data) {
		var valueData = [
			{'name':'公立', 'value':0},{'name':'民营', 'value':0}
		];

		var nameData = [];
		for(var i=0; i < valueData.length; i++){
			nameData.push(valueData[i].name);
		}

		if (data.publicCnt != undefined) {
			valueData[0].value = data.publicCnt;
		}

		if (data.privateCnt != undefined) {
			valueData[1].value = data.privateCnt;
		}

		// 1. 实例化对象
		var myChart = echarts.init(document.querySelector("#economicPie"));
		// 2. 指定配置项和数据
		option = {
			tooltip : {
				trigger: 'item',
				formatter: "{b}<br/>{c} ({d}%)"
			},
			color: [
				mainColor,
				"#217eff",
			],
			series : [
				{
					name:'',
					type:'pie',
					center: ["50%", "50%"],
					radius : ['45%', '70%'],
					labelLine : {
						show : true,
						normal:{
							// length: 20,  // 改变标示线的长度
							lineStyle: {
								color: mainColor  // 改变标示线的颜色
							}
						},
					},
					itemStyle : {
						normal : {
							label : {
								show : true,
								formatter: "{b}\n{c} ({d}%)",
								textStyle: {
									color: mainColor,  // 改变标示文字的颜色
									fontSize : fontChart(0.15)
								}
							},
						},
					},
					data:valueData
				}
			]
		};
		// 3. 配置项和数据给我们的实例化对象
		myChart.setOption(option);
		// 4. 当我们浏览器缩放的时候，图表也等比例缩放
		window.addEventListener("resize", function() {
			// 让我们的图表调用 resize这个方法
			myChart.resize();
		});
	};

	//性质
	function drawOwnershipBar(data) {
		if (data == null || data.length == 0) {
			return;
		} else {
			var nameData = [];
			var valueData = [];
			for(i=0;i<data.length;i++){
				nameData.push(data[i].name);
				valueData.push(data[i]);
			}
		}
		// 1. 实例化对象
		var myChart = echarts.init(document.querySelector("#natureBar"));
		// 2. 指定配置项和数据
		option = {
			title: {
				subtext: '机构数',
				subtextStyle: {
					color: mainColor,
				}
			},
			grid:{
				x: 40,
				y: 60,
				x2: 15,
				y2: 40,
			},
			tooltip : {
				trigger: 'axis'
			},
			calculable : true,
			xAxis : [
				{
					type : 'category',
					data : nameData,
					axisLine: {
						lineStyle: {
							color: mainColor
						}
					},
					splitLine: {
						show: false
					},
					axisTick:{
						show:false
					},
				}
			],
			yAxis : [
				{
					type : 'value',
					minInterval: 1,
					axisLine: {
						lineStyle: {
							color: mainColor
						}
					},
					splitLine: {
						show: false
					},
					axisTick:{
						show:false
					},
				}
			],
			series : [
				{
					name:'机构数',
					type:'bar',
					data:valueData,
					itemStyle: {
						normal: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
								offset: 0,
								color: mainColor
							}, {
								offset: 1,
								color: '#195bff'
							}]),
						}
					},
					barWidth: fontChart(0.5),
				}
			]
		};

		// 3. 配置项和数据给我们的实例化对象
		myChart.setOption(option);
		// 4. 当我们浏览器缩放的时候，图表也等比例缩放
		window.addEventListener("resize", function() {
			// 让我们的图表调用 resize这个方法
			myChart.resize();
		});
	};

	//街道分布
	function drawDistributionPolar(data) {
		if (data.length == 0) {
			return;
		} else {
			var nameData = [];
			for(i=0;i<data.length;i++){
				nameData.push(data[i].name);
			}
		}
		// 1. 实例化对象
		var myChart = echarts.init(document.querySelector("#distributionPolar"));
		// 2. 指定配置项和数据
		option = {
			tooltip: {
				trigger: 'item',
			},
			angleAxis: {//极坐标系的角度轴
				boundaryGap: ['50%', '50%'],
				type: 'category',
				startAngle: 90,
				splitNumber: 24, //坐标轴分割段数
				axisLine: { //坐标轴轴线设置
					lineStyle: {
						color: 'rgba(255, 255, 255, 0.6)',
					}
				},
				axisTick: { //坐标轴刻度设置
					show: true,
					interval: 2,
				},
				splitLine: { //分割线设置
					show: false,
				},
				axisLabel: { //刻度标签设置
					textStyle: {
						color: mainColor
					}
				},
				data: nameData
			},
			radiusAxis: {
				min: 0,
				minInterval: 1,
				axisLine: { //坐标轴轴线设置
					show: true,
					lineStyle: {
						color: 'rgba(255, 255, 255, 0.6)'
					}
				},
				axisTick: { //坐标轴刻度设置
					show: true
				},
				axisLabel: { //刻度标签设置
					margin: 5, //刻度与坐标轴之间的距离
					textStyle: {
						color: mainColor
					}
				},
			},
			polar: {
				center: ['50%', '50%'],
			},
			series: [{
				type: 'bar',
				data: data,
				coordinateSystem: 'polar',
				lineStyle: {
					normal: {
						color: 'rgba(255, 255, 255, 0.9)'
					}
				},
				itemStyle: {
					normal: {
							color: mainColor
					}
				},
				animationDuration: 2000
			}],
		};

		// 3. 配置项和数据给我们的实例化对象
		myChart.setOption(option);
		// 4. 当我们浏览器缩放的时候，图表也等比例缩放
		window.addEventListener("resize", function() {
			// 让我们的图表调用 resize这个方法
			myChart.resize();
		});
	}

	//轮动
	function drawCarousel(data) {
			if (data == null || data.length == 0) {
				return;
			}

			//清空
			// document.getElementById("lunbo").innerHTML = "";

			for(var i = 0; i < data.length; i++) {
				var pieId = "institutionPie" + i;
				var barId = "institutionBar" + i;
				var common = "<div class='bottomTitle_img'>" +
					"<span class='bottomTitleFont'>" + data[i].name + "</span></div>" +
					"<div class='bottomCharts'>" +
					"<div class='bottomLeftChart'>" +
					"<div class='bottomLeftChartInner' id='" + pieId + "'></div>" +
					"</div>" + "<div class='bottomRightChart' id='" + barId + "'></div>" + "</div>" + "</div>";

				var obj = document.getElementById(pieId);
				if(obj == null) {
					if(i == 0) {
						$("#lunbo").append(
							"<div class='item active'>" + common
						);
					} else {
						$("#lunbo").append(
							"<div class='item'>" + common
						);
					}
				}

				drawInstitutionPie(data[i], "#" + pieId);
				drawInstitutionBar(data[i], "#" + barId);
			}
		}

	//街道机构数
	function drawInstitutionPie(data, id) {
		if (data.length == 0) {
			return;
		} else {

			var nameData = [];
			var valueData = [];
			nameData.push("");
			valueData.push(data.value);
			nameData.push("");
			valueData.push(quantity - data.value);
		}
		// 1. 实例化对象
		var myChart = echarts.init(document.querySelector(id));
		// 2. 指定配置项和数据
		option = {
			title: {
				text: '街道医疗机构数',
				x: 'center',
				textStyle: {
					fontSize: fontChart(0.175),
					fontStyle: 'normal',
					fontWeight: 'normal',
					color: '#fff',
				},
			},
			tooltip : {
				trigger: 'item',
				formatter: "{c} ({d}%)"
			},
			color: [
				'#F2828E',
				'#558FF0',
			],
			series : [
				{
					name:'',
					type:'pie',
					center: ["50%", "55%"],
					radius : ['45%', '70%'],
					labelLine : {
						show : true,
						normal:{
							// length: 30,  // 改变标示线的长度
							lineStyle: {
								color: '#fff'  // 改变标示线的颜色
							}
						},
					},
					itemStyle : {
						normal : {
							label : {
								show : true,
								formatter: "{b}\n{c} ({d}%)",
								textStyle: {
									color: '#fff',  // 改变标示文字的颜色
									fontSize: fontChart(0.15),
								}
							},
						},
					},
					data:valueData
				}
			]
		};
		// 3. 配置项和数据给我们的实例化对象
		myChart.setOption(option);
		// 4. 当我们浏览器缩放的时候，图表也等比例缩放
		window.addEventListener("resize", function() {
			// 让我们的图表调用 resize这个方法
			myChart.resize();
		});
	};

	//街道机构性质
	function drawInstitutionBar(data, id) {
		if (data.length == 0) {
			return;
		} else {
			var nameData = [];
			var valueData = [];
			if(data.ownership.length == 0)
				return;
			var temp = data.ownership.split(',');
			for(i=0;i<temp.length;i++){
				var one = temp[i].split('/');
				if (one.length < 2)
					return;
				nameData.push(one[0]);
				valueData.push(one[1]);
			}
		}
		// 1. 实例化对象
		var myChart = echarts.init(document.querySelector(id));
		// 2. 指定配置项和数据
		option = {
			title: {
				subtext: '机构数',
				subtextStyle: {
					color: '#fff',
				}
			},
			grid:{
				x: 40,
				y: 60,
				x2: 15,
				y2: 40,
			},
			tooltip : {
				trigger: 'axis'
			},
			calculable : true,
			xAxis : [
				{
					type : 'category',
					data : nameData,
					axisLabel: {
						textStyle: {
							color: '#fff'
						}
					},
					axisLine: {
						lineStyle: {
							color: mainColor
						}
					},
					splitLine: {
						show: false
					},
					axisTick:{
						show:false
					},
				}
			],
			yAxis : [
				{
					type : 'value',
					minInterval: 1,
					axisLabel: {
						textStyle: {
							color: '#fff'
						}
					},
					axisLine: {
						lineStyle: {
							color: mainColor
						}
					},
					splitLine: {
						show: false
					},
					axisTick:{
						show:false
					},
				}
			],
			series : [
				{
					name:'机构数',
					type:'bar',
					data:valueData,
					itemStyle: {
						normal: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
								offset: 0,
								color: '#F2828E'
							}, {
								offset: 0.7,
								color: '#558FF0'
							}]),
						}
					},
					barWidth: fontChart(0.5),
				}
			]
		};

		// 3. 配置项和数据给我们的实例化对象
		myChart.setOption(option);
		// 4. 当我们浏览器缩放的时候，图表也等比例缩放
		window.addEventListener("resize", function() {
			// 让我们的图表调用 resize这个方法
			myChart.resize();
		});
	};

	function setSelectpickerOptions(data) {
		setOptionsCommon('street', data.district);
		setOptionsCommon('industry', data.industry);
		setOptionsCommon('level', data.level);
		setOptionsCommon('economic', data.economic);
		setOptionsCommon('ownership', data.ownership);
		$('.selectpicker').selectpicker('refresh');
	}

	function setOptionsCommon(name, data) {
		if (data == undefined) {
			return;
		}

		if (name == 'economic') {
			document.getElementById("economicOption0").textContent = "公立 (" + data.publicCnt + ")";
			document.getElementById("economicOption1").textContent = "民营 (" + data.privateCnt + ")";
		} else {
			var ele = $("#"+name + "Select");
			for (var i=0; i < data.length; i++) {
				var id = name + 'Option' + data[i].id;
				var element = document.getElementById(id);
				if (element) {
					element.textContent =  data[i].name + " (" + data[i].value + ")";
				} else {
					ele.append("<option value=" + data[i].id + " id=" + id + ">" + data[i].name + " (" + data[i].value + ")</option>");
				}
			}
		}
	}

	function getParamsSearch(searchKey, currentPage, limit) {
		var params = {};

		params.searchKey = searchKey;
		params.currentPage = currentPage;
		params.limit = limit;
		params.street = $('#streetSelect').find("option:selected").val();
		params.industry = $('#industrySelect').find("option:selected").val();
		params.economic = $('#economicSelect').find("option:selected").val();
		params.level = $('#levelSelect').find("option:selected").val();
		params.ownership = $('#ownershipSelect').find("option:selected").val();

		return params;
	}

	function searchLoad(target, searchKey, currentPage) {
		var limit = 10;
		var $that = target;
		var params = getParamsSearch(searchKey, currentPage, limit);
		$.ajax({
			type: "POST",
			url: "invs_home_page.do/dispaly_search_login",
			data: params,
			success: function(data) {
				WeKnow.closeLoading();
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

				if (data.errorcode == 0) {
					var institutionList = data.institutionList;
					var total = data.total;
					$('#searchList').empty();
					if (institutionList == null || institutionList.length == 0 ) {
						//
					} else {

						$(institutionList).each(function (idx, g) {
							$((function () {
								var e = '';
								e += '<tr class="search-tr">';
								e += '<td class="search-td">' + g.name + '</td>';
								e += '<td style="display:none">' + g.id + '</td>';
								e += '</tr>';
								return e;
							})()).appendTo($('#searchList')).on('click', function () {
								$('input#insitutionNameSearch').val(g.name);
								$('button#institutionDetails').attr("data-institutionname", g.name);
								$('button#institutionDetails').attr("data-institutionid", g.id);

								//判断状态是否为全屏
								var screenState = $("#full_scr").is(":hidden") ? 'fullScreen' : 'exitFullScreen';
								WeKnow.submit(
									'invs_institution_details.do',
									{
										screenState: screenState,
										pageId: "institutionReview",
										institutionName: g.name,
										institutionId: g.id,
									}
								);
							});
						});
					}

					// $('.selectpicker').selectpicker('refresh');

					if (total > limit) {
						$('div.layui-table-page').show();
					} else {
						$('div.layui-table-page').hide();
					}

					layui.use('laypage', function(){
						var laypage = layui.laypage;
						//执行一个laypage实例
						laypage.render({
							elem: 'searchPagination',
							count: total,
							limit: limit,
							curr: currentPage,
							// theme: 'rgb(46,76,255)',
							jump: function (obj, first) { //obj为当前页的属性和方法，第一次加载first为true
								//非首次加载 do something
								if (!first) {
									//清空以前加载的数据
									$('#searchList').empty();
									//调用加载函数加载数据
									MY_INSTITUTION_REVIEW.searchLoad($that, searchKey, obj.curr);
								}
							}
						});
					});

				} else if (data.errorcode == -1 ) {
					WeKnow.errorMsg( data.errMsg );
				} else {
					WeKnow.systemMsg('查询失败，请重新登录');
				}
			}
		});
	}

	//自适应字体大小
	function fontChart(res) {
		//获取到屏幕的宽度
		var clientWidth =
			window.innerWidth ||
			document.documentElement.clientWidth ||
			document.body.clientWidth;
		if (!clientWidth) return; //报错拦截：
		var fontSize = 80 * (clientWidth / screen.width);
		return res * fontSize;
	}

	return {
		loadChartInfo:loadChartInfo,
		searchLoad:searchLoad,
	}
})();

$(document).ready(function() {

	MY_MAP.initMap("institution_review");
	MY_INSTITUTION_REVIEW.loadChartInfo();
	setInterval(function(){ MY_INSTITUTION_REVIEW.loadChartInfo(); }, 5000);

	$('#economicSelect, #ownershipSelect, #levelSelect').selectpicker({
		width: MY_HOME_PAGE_COMMON.fontChart(1.5)
	});

	$('#industrySelect, #streetSelect').selectpicker({
		width: MY_HOME_PAGE_COMMON.fontChart(2)
	});

	$('.selectpicker').on('change',function(){
		$("input#insitutionNameSearch").trigger("click");
	});

	$("#institutionDetails").on('click',function () {
		$("input#insitutionNameSearch").trigger("click");
	});

	var autoSearch;
	$('input#insitutionNameSearch').on('input click', function () {

		if (document.getElementById("searchMenu").style.display == 'none') {
			document.getElementById("searchMenu").style.display = 'inline';
		}

		if (autoSearch) {
			clearTimeout(autoSearch);
		}

		var $that = $(this);
		var searchKey = $.trim($that.val());
		autoSearch = setTimeout(MY_INSTITUTION_REVIEW.searchLoad($that, searchKey, 1), 500);
	});

	$("#container, div[class$='Chart']").on('click', function(e) {
		if (document.getElementById("searchMenu").style.display == 'inline') {
			document.getElementById("searchMenu").style.display = 'none';
		}
	});
});
